import * as Print from 'expo-print';
import * as Sharing from 'expo-sharing';
import { Alert } from 'react-native';

// 健康数据类型定义
export interface HealthDataForPdf {
  heartRate?: number;
  bloodPressureDiastolic?: number;
  bloodPressureSystolic?: number;
  bloodOxygen?: number;
  stressIndex?: number;
  heartAttackIndex?: number;
  reactionTime?: number;
  gripStrength?: number;
  flicker?: number;
  vitalCapacity?: number;
  alcohol?: number;
  healthIndex?: number;
  emotionIndex?: number;
  fatigueIndex?: number;
  overallIndex?: number;
}

// 用户信息类型定义
export interface UserInfoForPdf {
  nickname?: string;
  id?: string;
  avatar?: string;
  mobile?: string;
  sex?: number | string;
  age?: number;
}

// 健康状态评估函数 - 与结果页面保持一致
const getHealthStatus = (metricType: string, value: number): string => {
    switch (metricType) {
        case 'heartRate':
            if (value < 60) return '偏低';
            if (value > 100) return '偏高';
            return '正常';
        case 'bloodPressureLow':
            if (value < 90) return '偏低';
            if (value > 140) return '偏高';
            return '正常';
        case 'bloodPressureHigh':
            if (value < 60) return '偏低';
            if (value > 90) return '偏高';
            return '正常';
        case 'spo2':
            if (value < 95) return '偏低';
            return '正常';
        case 'reactionTime':
            if (value > 600) return '偏高';
            return '正常';
        case 'gripStrength':
            if (value < 20) return '偏低';
            if (value > 50) return '偏高';
            return '正常';
        case 'vitalCapacity':
            if (value < 2500) return '偏低';
            return '正常';
        default:
            return '正常';
    }
};

// 评分等级函数 - 与结果页面保持一致
const getRating = (score: number): string => {
    if (score >= 85) return '优';
    if (score >= 68 && score < 85) return '良';
    return '差';
};

/**
 * 导出健康检测报告为PDF
 * @param healthData 健康数据
 * @param userInfo 用户信息
 * @param testTime 检测时间
 * @param setIsExportingPdf 设置导出状态的函数
 * @param standardData 标准值数据
 */
export const exportHealthReportToPdf = async (
  healthData: HealthDataForPdf,
  userInfo: UserInfoForPdf,
  testTime: string,
  setIsExportingPdf: (value: boolean) => void,
  standardData?: {
    heartRate?: number;
    oxygenSaturation?: number;
    systolicPressure?: number;
    diastolicPressure?: number;
    vitalCapacity?: number;
    gripStrength?: number;
    reactionTime?: number;
    breathAlcohol?: number;
    stress?: number;
    richSore1?: number;
  }
): Promise<void> => {
  console.log('exportHealthReportToPdf函数被调用');
  setIsExportingPdf(true);
  try {
    console.log('开始处理PDF导出');
    // 从healthData中获取各项指标值
    const heartRate = healthData.heartRate;
    const bloodPressureLow = healthData.bloodPressureDiastolic;
    const bloodPressureHigh = healthData.bloodPressureSystolic;
    const spo2 = healthData.bloodOxygen;
    const stressIndex = healthData.stressIndex;
    const heartAttackIndex = healthData.heartAttackIndex;
    const reactionTime = healthData.reactionTime;
    const gripStrength = healthData.gripStrength;
    const flicker = healthData.flicker;
    const vitalCapacity = healthData.vitalCapacity;
    const alcohol = healthData.alcohol;

    // 从传递过来的数据中获取各项判定分，如果没有则使用默认值0
    const heartRateScore = healthData.heartRateScore || 0;
    const bloodPressureLowScore = healthData.bloodPressureLowScore || 0;
    const bloodPressureHighScore = healthData.bloodPressureHighScore || 0;
    const spo2Score = healthData.spo2Score || 0;
    const stressIndexScore = healthData.stressIndexScore || 0;
    const heartAttackRiskScore = healthData.heartAttackRiskScore || 0;
    const reactionTimeScore = healthData.reactionTimeScore || 0;
    const gripStrengthScore = healthData.gripStrengthScore || 0;
    const flickerScore = healthData.flickerScore || 0;
    const vitalCapacityScore = healthData.vitalCapacityScore || 0;
    const alcoholScore = healthData.alcoholScore || 0;

    // 计算指数（如果未提供）
    const calculateHealthIndex = (
      heartRateScore: number,
      bloodPressureScore: number,
      spo2Score: number,
      stressIndexScore: number,
      heartAttackRiskScore: number
    ): number => {
      return (heartRateScore + bloodPressureScore + spo2Score + stressIndexScore + heartAttackRiskScore) / 5;
    };

    const calculateFatigueIndex = (
      flickerScore: number,
      alcoholScore: number,
      reactionTimeScore: number,
      gripStrengthScore: number,
      vitalCapacityScore: number
    ): number => {
      return (flickerScore + alcoholScore + reactionTimeScore + gripStrengthScore + vitalCapacityScore) / 5;
    };

    const calculateOverallIndex = (
      healthIndex: number,
      emotionIndex: number,
      fatigueIndex: number
    ): number => {
      return (healthIndex + emotionIndex + fatigueIndex) / 3;
    };

    // 优先使用传递过来的已计算好的指数值，如果没有则自己计算
    const healthIndex = typeof healthData.healthIndex === 'number' ? 
      healthData.healthIndex : 
      calculateHealthIndex(heartRateScore, (bloodPressureLowScore + bloodPressureHighScore) / 2, spo2Score, stressIndexScore, heartAttackRiskScore);
    
    const emotionIndex = typeof healthData.emotionIndex === 'number' ? 
      healthData.emotionIndex : 
      stressIndexScore;
    
    const fatigueIndex = typeof healthData.fatigueIndex === 'number' ? 
      healthData.fatigueIndex : 
      calculateFatigueIndex(flickerScore, alcoholScore, reactionTimeScore, gripStrengthScore, vitalCapacityScore);
    
    const overallIndex = typeof healthData.overallIndex === 'number' ? 
      healthData.overallIndex : 
      calculateOverallIndex(healthIndex, emotionIndex, fatigueIndex);

    // 确保所有值都是有效数字
    const safeHealthIndex = isNaN(healthIndex) || !isFinite(healthIndex) ? 0 : healthIndex;
    const safeEmotionIndex = isNaN(emotionIndex) || !isFinite(emotionIndex) ? 0 : emotionIndex;
    const safeFatigueIndex = isNaN(fatigueIndex) || !isFinite(fatigueIndex) ? 0 : fatigueIndex;
    const safeOverallIndex = isNaN(overallIndex) || !isFinite(overallIndex) ? 0 : overallIndex;

    // 获取健康状态样式 - 与结果页面保持一致
    const getHealthStatusStyle = (metricType: string, value: number) => {
        const status = getHealthStatus(metricType, value);
        if (status === '正常') return '#2E7D32'; // 绿色
        if (status === '偏高') return '#E65100'; // 橙色
        if (status === '偏低') return '#0D47A1'; // 蓝色
        return '#2E7D32'; // 默认绿色
    };

    // 获取右上角评级样式 - 与结果页面保持一致
    const getTopRightRatingStyle = (index: number) => {
        if (index >= 85) return '#4CAF50'; // 绿色
        if (index >= 68 && index < 85) return '#87CEEB'; // 浅蓝色
        return '#FF5252'; // 红色
    };

    // 获取评级样式 - 与结果页面保持一致
    const getRatingStyle = (index: number) => {
        if (index >= 85) return '#2E7D32'; // 深绿色
        if (index >= 68) return '#1565C0'; // 深蓝色
        return '#C62828'; // 深红色
    };

    // 创建HTML内容 - 优化布局，解决卡片间距和内部布局问题
    const htmlContent = `
      <html>
        <head>
          <meta charset="UTF-8">
          <style>
            body { 
              font-family: Arial, sans-serif; 
              padding: 12px; 
              margin: 0; 
              background-color: #f5f5f5;
              color: #333;
              font-size: 14px;
            }
            .container {
              max-width: 100%;
              margin: 0 auto;
              background-color: #fff;
            }
            .header-card {
              background-color: #fff;
              margin: 10px;
              margin-top: 18px;
              border-radius: 10px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.1);
              overflow: hidden;
            }
            .header-top {
              display: flex;
              justify-content: space-between;
              align-items: center;
              background-color: #4285F4;
              padding: 8px 16px;
            }
            .title {
              font-size: 18px;
              color: #fff;
              font-weight: bold;
            }
            .header-content {
              display: flex;
              padding: 14px;
            }
            .user-info-card {
              flex: 1;
              background-color: #fff;
              border-radius: 10px;
              padding: 14px;
              margin-right: 14px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.08);
              border-left: 4px solid #4285F4;
            }
            .user-info-header {
              display: flex;
              align-items: center;
            }
            .user-details {
              flex: 1;
            }
            .user-name {
              font-size: 18px;
              font-weight: 700;
              color: #1a1a1a;
              margin-bottom: 7px;
            }
            .user-info-row {
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              gap: 7px;
              margin-bottom: 5px;
            }
            .user-id-container {
              display: flex;
              align-items: center;
              background-color: #f5f5f5;
              align-self: flex-start;
              padding: 3px 8px;
              border-radius: 10px;
            }
            .user-id-label {
              font-size: 12px;
              color: #666;
              font-weight: 500;
            }
            .user-id-separator {
              font-size: 12px;
              color: #999;
              margin: 0 4px;
            }
            .user-id {
              font-size: 12px;
              color: #333;
              font-weight: 500;
            }
            .avatar-container {
              margin-left: 14px;
            }
            .avatar-placeholder {
              width: 55px;
              height: 55px;
              border-radius: 28px;
              background-color: #4285F4;
              display: flex;
              justify-content: center;
              align-items: center;
              border: 2px solid #f0f0f0;
            }
            .avatar-text {
              font-size: 22px;
              font-weight: bold;
              color: #fff;
            }
            .score-card {
              flex: 0.4;
              background-color: #fff;
              border-radius: 10px;
              padding: 14px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.08);
              border-left: 4px solid #4285F4;
            }
            .score-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;
            }
            .score-title {
              font-size: 14px;
              font-weight: 600;
              color: #333;
            }
            .score-content {
              display: flex;
              align-items: center;
              justify-content: space-around;
              margin-top: 7px;
            }
            .score-circle-container {
              display: flex;
              align-items: center;
              flex: 1;
            }
            .score-circle {
              width: 55px;
              height: 55px;
              border-radius: 28px;
              display: flex;
              justify-content: center;
              align-items: center;
              box-shadow: 0 2px 4px rgba(0,0,0,0.15);
              margin: 0 auto;
            }
            .score-value {
              font-size: 17px;
              font-weight: bold;
              color: #fff;
            }
            .score-details {
              display: flex;
              align-items: center;
              flex: 1;
            }
            .score-index-label {
              font-size: 13px;
              color: #666;
              margin-bottom: 4px;
              font-weight: 500;
            }
            .score-index-container {
              display: flex;
              align-items: baseline;
            }
            .score-index-value {
              font-size: 22px;
              font-weight: bold;
              color: #333;
            }
            .score-index-unit {
              font-size: 13px;
              color: #666;
              margin-left: 3px;
            }
            .section-card {
              background-color: #fff;
              margin: 10px;
              border-radius: 10px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.1);
              overflow: hidden;
            }
            .section-content {
              padding: 8px;
              background-color: #fff;
            }
            .section-header-top {
              display: flex;
              justify-content: space-between;
              align-items: center;
              background-color: #4285F4;
              padding: 8px 16px;
            }
            .section-title {
              font-size: 18px;
              font-weight: bold;
              color: #fff;
            }
            .status-network {
              display: flex;
              flex-wrap: wrap;
              justify-content: space-between;
              margin: 0;
              padding: 0 8px;
            }
            .grid-item {
              width: 31.5%;
              background-color: #fff;
              border-radius: 8px;
              padding: 12px;
              margin-bottom: 10px;
              margin-right: 1%;
              display: flex;
              flex-direction: column;
              align-items: center;
              box-shadow: 0 2px 4px rgba(0,0,0,0.06);
              border-left: 4px solid #4285F4;
              box-sizing: border-box;
            }
            .grid-item:nth-child(3n) {
              margin-right: 0;
            }
            .item-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
              margin-bottom: 8px;
            }
            .item-title {
              font-size: 14px;
              color: #555;
              font-weight: 500;
            }
            .item-value {
              font-size: 20px;
              color: #1a1a1a;
              font-weight: 700;
              margin-bottom: 3px;
              text-align: center;
            }
            .item-unit {
              font-size: 12px;
              color: #888;
            }
            .baseline-value {
              font-size: 14px;
              color: #888;
              font-weight: normal;
            }
            .score-badge {
              padding: 3px 6px;
              border-radius: 10px;
              min-width: 20px;
              height: 20px;
              display: flex;
              justify-content: center;
              align-items: center;
              box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            }
            .score-badge-text {
              font-size: 10px;
              font-weight: bold;
              color: #fff;
            }
            .evaluation-grid {
              display: flex;
              justify-content: space-between;
              margin: 0;
              padding: 0 8px;
            }
            .evaluation-card {
              width: 31.5%;
              background-color: #fff;
              border-radius: 8px;
              padding: 12px;
              margin-right: 1%;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              box-shadow: 0 2px 4px rgba(0,0,0,0.08);
              border-left: 4px solid #4285F4;
              min-height: 80px;
              box-sizing: border-box;
            }
            .evaluation-card:last-child {
              margin-right: 0;
            }
            .evaluation-row {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
            }
            .evaluation-icon-container {
              width: 30px;
              height: 30px;
              border-radius: 15px;
              display: flex;
              justify-content: center;
              align-items: center;
              margin-right: 7px;
            }
            .evaluation-icon {
              font-size: 18px;
              font-weight: bold;
            }
            .evaluation-text-container {
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            }
            .evaluation-card-title {
              font-size: 13px;
              font-weight: 600;
              color: #333;
              margin-bottom: 5px;
              text-align: center;
            }
            .evaluation-card-value {
              font-size: 18px;
              font-weight: 700;
              color: #1a1a1a;
              text-align: center;
            }
            .disclaimer-container {
              padding: 8px;
              display: flex;
              justify-content: space-between;
            }
            .disclaimer-section {
              width: 48%;
              background-color: #f9f9f9;
              border-radius: 8px;
              padding: 8px;
              border-left: 4px solid #4285F4;
            }
            .disclaimer-title {
              font-size: 13px;
              font-weight: 600;
              color: #333;
              margin-bottom: 5px;
            }
            .disclaimer-text {
              font-size: 11px;
              color: #666;
              line-height: 14px;
              text-align: justify;
            }
            .not-tested {
              background-color: #9E9E9E;
            }
            .not-tested-text {
              font-size: 14px;
              color: #757575;
              font-weight: 500;
              font-style: italic;
            }
            .footer {
              margin-top: 18px;
              text-align: center;
              font-size: 11px;
              color: #888;
              padding: 8px;
            }
            /* 健康指标卡片颜色 */
            .heart-rate-card { border-left-color: #F44336; }
            .blood-pressure-card { border-left-color: #9C27B0; }
            .spo2-card { border-left-color: #2196F3; }
            .stress-index-card { border-left-color: #FF9800; }
            .heart-attack-card { border-left-color: #D32F2F; }
            .reaction-time-card { border-left-color: #00BCD4; }
            .grip-strength-card { border-left-color: #4CAF50; }
            .flicker-card { border-left-color: #FFC107; }
            .vital-capacity-card { border-left-color: #3F51B5; }
            .alcohol-card { border-left-color: #E91E63; }
            .health-index-card { border-left-color: #4CAF50; }
            .emotion-index-card { border-left-color: #9C27B0; }
            .fatigue-index-card { border-left-color: #FF9800; }
          </style>
        </head>
        <body>
          <div class="container">
            <!-- 头部信息和综合评分 -->
            <div class="header-card">
              <div class="header-top">
                <div class="title">检测结果</div>
              </div>
              <div class="header-content">
                <div class="user-info-card">
                  <div class="user-info-header">
                    <div class="user-details">
                      <div class="user-name">${userInfo.nickname || '未知用户'}</div>
                      <div class="user-info-row">
                        <div class="user-id-container">
                          <span class="user-id-label">ID</span>
                          <span class="user-id-separator">•</span>
                          <span class="user-id">${userInfo.id || '-'}</span>
                        </div>
                        ${userInfo.mobile ? `
                        <div class="user-id-container">
                          <span class="user-id-label">电话</span>
                          <span class="user-id-separator">•</span>
                          <span class="user-id">${userInfo.mobile}</span>
                        </div>` : ''}
                        ${userInfo.sex ? `
                        <div class="user-id-container">
                          <span class="user-id-label">性别</span>
                          <span class="user-id-separator">•</span>
                          <span class="user-id">${userInfo.sex === 1 || userInfo.sex === 'male' ? '男' : '女'}${userInfo.age ? ' ' + userInfo.age + '岁' : ''}</span>
                        </div>` : ''}
                      </div>
                      <div class="user-info-row">
                        <div class="user-id-container">
                          <span class="user-id-label">检测时间</span>
                          <span class="user-id-separator">•</span>
                          <span class="user-id">${testTime}</span>
                        </div>
                      </div>
                    </div>
                    <div class="avatar-container">
                      <div class="avatar-placeholder">
                        <span class="avatar-text">${(userInfo.nickname || '未知用户').charAt(0)}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="score-card">
                  <div class="score-header">
                    <div class="score-title">今日检测结果</div>
                  </div>
                  <div class="score-content">
                    <div class="score-circle-container">
                      <div class="score-circle" style="background-color: ${getTopRightRatingStyle(safeOverallIndex)}">
                        <div class="score-value">${getRating(safeOverallIndex)}</div>
                      </div>
                    </div>
                    <div class="score-details">
                      <div class="score-index-label">综合指数</div>
                      <div class="score-index-container">
                        <div class="score-index-value">${safeOverallIndex}</div>
                        <div class="score-index-unit">分</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 健康指标详情 -->
            <div class="section-card">
              <div class="section-header-top">
                <div class="section-title">健康指标详情</div>
              </div>
              <div class="section-content">
                <div class="status-network">
                  <!-- 心率卡片 -->
                  <div class="grid-item heart-rate-card">
                    <div class="item-header">
                      <div class="item-title">心率</div>
                      <div class="score-badge" style="background-color: ${heartRate !== undefined && heartRate !== 0 ? getHealthStatusStyle('heartRate', heartRate) : '#9E9E9E'}">
                        <span class="score-badge-text">${heartRate !== undefined && heartRate !== 0 ? getHealthStatus('heartRate', heartRate) : '未测试'}</span>
                      </div>
                    </div>
                    <div class="${heartRate !== undefined && heartRate !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${heartRate !== undefined && heartRate !== 0 ? 
                        `${heartRate}<span class="baseline-value">(${standardData?.heartRate || '-'})</span><span class="item-unit">bpm</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 血氧卡片 -->
                  <div class="grid-item spo2-card">
                    <div class="item-header">
                      <div class="item-title">血氧</div>
                      <div class="score-badge" style="background-color: ${spo2 !== undefined && spo2 !== 0 ? getHealthStatusStyle('spo2', spo2) : '#9E9E9E'}">
                        <span class="score-badge-text">${spo2 !== undefined && spo2 !== 0 ? getHealthStatus('spo2', spo2) : '未测试'}</span>
                      </div>
                    </div>
                    <div class="${spo2 !== undefined && spo2 !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${spo2 !== undefined && spo2 !== 0 ? 
                        `${spo2}<span class="baseline-value">(${standardData?.oxygenSaturation || '-'})</span><span class="item-unit">%</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 压力指数卡片 -->
                  <div class="grid-item stress-index-card">
                    <div class="item-header">
                      <div class="item-title">压力指数</div>
                      <div class="score-badge" style="background-color: ${stressIndex !== undefined && stressIndex !== 0 ?
                        (stressIndex <= 2.5 ? '#2E7D32' : stressIndex < 3 ? '#1565C0' : stressIndex < 4 ? '#F57C00' : '#C62828') :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${stressIndex !== undefined && stressIndex !== 0 ?
                          (stressIndex <= 2.5 ? '低' : stressIndex < 3 ? '正常' : stressIndex < 4 ? '偏高' : '高') :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${stressIndex !== undefined && stressIndex !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${stressIndex !== undefined && stressIndex !== 0 ? 
                        `${stressIndex}<span class="baseline-value">(${standardData?.stress || '-'})</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 心康指数卡片 -->
                  <div class="grid-item heart-attack-card">
                    <div class="item-header">
                      <div class="item-title">心康指数</div>
                      <div class="score-badge" style="background-color: ${heartAttackIndex !== undefined && heartAttackIndex !== 0 ?
                        (heartAttackRiskScore === 100 ? '#2E7D32' : '#C62828') :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${heartAttackIndex !== undefined && heartAttackIndex !== 0 ?
                          (heartAttackRiskScore === 100 ? '低风险' : '高风险') :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${heartAttackIndex !== undefined && heartAttackIndex !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${heartAttackIndex !== undefined && heartAttackIndex !== 0 ? 
                        `${heartAttackIndex}<span class="baseline-value">(${standardData?.richSore1 || '-'})</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 视觉疲劳检测卡片 -->
                  <div class="grid-item flicker-card">
                    <div class="item-header">
                      <div class="item-title">视觉疲劳</div>
                      <div class="score-badge" style="background-color: ${flicker !== undefined ?
                        (flicker === 1 ? '#2E7D32' : '#C62828') :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${flicker !== undefined ?
                          (flicker === 1 ? '正常' : '疲劳') :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${flicker !== undefined ? 'item-value' : 'not-tested-text'}">
                      ${flicker !== undefined ? 
                        (flicker === 1 ? '通过' : '未通过') : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 血压卡片 -->
                  <div class="grid-item blood-pressure-card">
                    <div class="item-header">
                      <div class="item-title">血压</div>
                      <div class="score-badge" style="background-color: ${(bloodPressureHigh !== undefined && bloodPressureLow !== undefined && bloodPressureHigh !== 0 && bloodPressureLow !== 0) ?
                        (getHealthStatus('bloodPressureLow', bloodPressureLow) === '正常' && getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '正常' ?
                          '#2E7D32' :
                          (getHealthStatus('bloodPressureLow', bloodPressureLow) === '偏低' || getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '偏低' ||
                            getHealthStatus('bloodPressureLow', bloodPressureLow) === '偏高' || getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '偏高') ?
                            '#C62828' : '#F57C00') :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${(bloodPressureHigh !== undefined && bloodPressureLow !== undefined && bloodPressureHigh !== 0 && bloodPressureLow !== 0) ?
                          (getHealthStatus('bloodPressureLow', bloodPressureLow) === '正常' && getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '正常' ?
                            '正常' :
                            (getHealthStatus('bloodPressureLow', bloodPressureLow) === '偏低' || getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '偏低' ||
                              getHealthStatus('bloodPressureLow', bloodPressureLow) === '偏高' || getHealthStatus('bloodPressureHigh', bloodPressureHigh) === '偏高') ?
                              '异常' : '一般') :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${(bloodPressureHigh !== undefined && bloodPressureLow !== undefined && bloodPressureHigh !== 0 && bloodPressureLow !== 0) ? 'item-value' : 'not-tested-text'}">
                      ${(bloodPressureHigh !== undefined && bloodPressureLow !== undefined && bloodPressureHigh !== 0 && bloodPressureLow !== 0) ? 
                        `${bloodPressureHigh}<span class="baseline-value">(${standardData?.systolicPressure || '-'})</span>/${bloodPressureLow}<span class="baseline-value">(${standardData?.diastolicPressure || '-'})</span><span class="item-unit">mmHg</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 反应时卡片 -->
                  <div class="grid-item reaction-time-card">
                    <div class="item-header">
                      <div class="item-title">反应时</div>
                      <div class="score-badge" style="background-color: ${reactionTime !== undefined && reactionTime !== 0 ?
                        getHealthStatusStyle('reactionTime', reactionTime) :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${reactionTime !== undefined && reactionTime !== 0 ?
                          getHealthStatus('reactionTime', reactionTime) :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${reactionTime !== undefined && reactionTime !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${reactionTime !== undefined && reactionTime !== 0 ? 
                        `${reactionTime}<span class="baseline-value">(${standardData?.reactionTime || '-'})</span><span class="item-unit">ms</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 握力卡片 -->
                  <div class="grid-item grip-strength-card">
                    <div class="item-header">
                      <div class="item-title">握力</div>
                      <div class="score-badge" style="background-color: ${gripStrength !== undefined && gripStrength !== 0 ?
                        getHealthStatusStyle('gripStrength', gripStrength) :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${gripStrength !== undefined && gripStrength !== 0 ?
                          getHealthStatus('gripStrength', gripStrength) :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${gripStrength !== undefined && gripStrength !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${gripStrength !== undefined && gripStrength !== 0 ? 
                        `${gripStrength}<span class="baseline-value">(${standardData?.gripStrength || '-'})</span><span class="item-unit">kg</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 肺活量卡片 -->
                  <div class="grid-item vital-capacity-card">
                    <div class="item-header">
                      <div class="item-title">肺活量</div>
                      <div class="score-badge" style="background-color: ${vitalCapacity !== undefined && vitalCapacity !== 0 ?
                        getHealthStatusStyle('vitalCapacity', vitalCapacity) :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${vitalCapacity !== undefined && vitalCapacity !== 0 ?
                          getHealthStatus('vitalCapacity', vitalCapacity) :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${vitalCapacity !== undefined && vitalCapacity !== 0 ? 'item-value' : 'not-tested-text'}">
                      ${vitalCapacity !== undefined && vitalCapacity !== 0 ? 
                        `${vitalCapacity}<span class="baseline-value">(${standardData?.vitalCapacity || '-'})</span><span class="item-unit">ml</span>` : 
                        '未测试'}
                    </div>
                  </div>

                  <!-- 酒精检测卡片 -->
                  <div class="grid-item alcohol-card">
                    <div class="item-header">
                      <div class="item-title">酒精含量</div>
                      <div class="score-badge" style="background-color: ${alcohol !== undefined ?
                        (alcohol === -1 ? '#C62828' : (alcohol <= 20 ? '#2E7D32' : '#C62828')) :
                        '#9E9E9E'}">
                        <span class="score-badge-text">${alcohol !== undefined ?
                          (alcohol === -1 ? '未检测' : (alcohol <= 20 ? '正常' : '超标')) :
                          '未测试'}</span>
                      </div>
                    </div>
                    <div class="${alcohol !== undefined ? 'item-value' : 'not-tested-text'}">
                      ${alcohol !== undefined ?
                        (alcohol === -1 ? '未检测' :
                          `${alcohol}<span class="baseline-value">(${standardData?.breathAlcohol || '-'})</span><span class="item-unit">mg/L</span>`) :
                        '未测试'}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 综合评估 -->
            <div class="section-card">
              <div class="section-header-top">
                <div class="section-title">综合评估</div>
              </div>
              <div class="section-content">
                <div class="evaluation-grid">
                  <div class="evaluation-card health-index-card">
                    <div class="evaluation-row">
                      <div class="evaluation-icon-container" style="background-color: rgba(76, 175, 80, 0.15)">
                        <span class="evaluation-icon" style="color: #4CAF50">♥</span>
                      </div>
                      <div class="evaluation-text-container">
                        <div class="evaluation-card-title">健康指数</div>
                        <div class="${healthIndex !== undefined ? 'evaluation-card-value' : 'not-tested-text'}">
                          ${healthIndex !== undefined ? safeHealthIndex : '未测试'}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="evaluation-card emotion-index-card">
                    <div class="evaluation-row">
                      <div class="evaluation-icon-container" style="background-color: rgba(156, 39, 176, 0.15)">
                        <span class="evaluation-icon" style="color: #9C27B0">☺</span>
                      </div>
                      <div class="evaluation-text-container">
                        <div class="evaluation-card-title">情绪指数</div>
                        <div class="${emotionIndex !== undefined ? 'evaluation-card-value' : 'not-tested-text'}">
                          ${emotionIndex !== undefined ? safeEmotionIndex : '未测试'}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="evaluation-card fatigue-index-card">
                    <div class="evaluation-row">
                      <div class="evaluation-icon-container" style="background-color: rgba(255, 152, 0, 0.15)">
                        <span class="evaluation-icon" style="color: #FF9800">⚡</span>
                      </div>
                      <div class="evaluation-text-container">
                        <div class="evaluation-card-title">疲劳指数</div>
                        <div class="${fatigueIndex !== undefined ? 'evaluation-card-value' : 'not-tested-text'}">
                          ${fatigueIndex !== undefined ? safeFatigueIndex : '未测试'}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 隐私声明和免责声明 -->
            <div class="section-card">
              <div class="section-header-top">
                <div class="section-title">隐私与免责声明</div>
              </div>
              <div class="section-content">
                <div class="disclaimer-container">
                  <div class="disclaimer-section">
                    <div class="disclaimer-title">隐私声明</div>
                    <div class="disclaimer-text">
                      我们重视您的隐私安全。您的健康数据将被加密存储，仅用于健康评估和改善建议。未经您的明确同意，我们不会向任何第三方分享您的个人健康信息。
                    </div>
                  </div>
                  
                  <div class="disclaimer-section">
                    <div class="disclaimer-title">免责声明</div>
                    <div class="disclaimer-text">
                      本应用提供的健康评估结果仅供参考，不能替代专业医疗诊断。如有健康问题，请咨询专业医疗机构。本应用不对因使用本评估结果而产生的任何后果承担责任。
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="footer">
            <p>本报告由AstraSafe安捷星健康检测系统生成</p>
          </div>
        </body>
      </html>
    `;

    // 生成PDF文件
    console.log('准备生成PDF文件');
    
    // 创建用户名加时间的文件名
    const userName = userInfo.nickname || '未知用户';
    // 清理文件名中的特殊字符
    const sanitizedUserName = userName.replace(/[^\w\u4e00-\u9fa5]/gi, '_');
    // 获取当前时间并格式化为 yyyyMMdd_HHmmss
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const timestamp = `${year}${month}${day}_${hours}${minutes}${seconds}`;
    
    // 生成自定义文件名：用户名_时间.pdf
    const fileName = `${sanitizedUserName}_${timestamp}`;
    
    const { uri } = await Print.printToFileAsync({
      html: htmlContent,
      base64: false,
    });
    console.log('PDF文件生成完成:', uri);

    // 分享PDF文件
    console.log('准备分享PDF文件');
    if (await Sharing.isAvailableAsync()) {
      await Sharing.shareAsync(uri, {
        mimeType: 'application/pdf',
        dialogTitle: '分享健康检测报告',
      });
      console.log('PDF文件分享完成');
    } else {
      Alert.alert('提示', '您的设备不支持分享功能');
    }
  } catch (error) {
    console.error('导出PDF失败:', error);
    Alert.alert('错误', `导出PDF失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
    setIsExportingPdf(false);
  }
};